package com.xxs.config;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.druid.filter.logging.Slf4jLogFilter;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallFilter;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.core.JFinal;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.jfinal.render.FreeMarkerRender;
import com.jfinal.render.ViewType;
import com.xxs.interceptor.GlobalInterceptor;
import com.xxs.model._MappingKit;
import com.xxs.template.PaginationDirective;
import com.xxs.template.ResourceListDirective;

import freemarker.template.Configuration;
import freemarker.template.TemplateModelException;
import freemarker.template.utility.StandardCompress;

/**
 * Created with IntelliJ IDEA.
 * 感谢 @波总 的JFinal，@闲.大赋 的beetl，向你们致敬！ ：）
 * 感谢 mike_liu 和 dream_lu，和众群友支持。
 * 如有问题，可以加 JFinal-BBS QQ群：206034609 讨论
 * 【4-3日，1.2版本】更新情况：
 * beetl和的JFinal都升级为最新版；加入了对自定义项目路径的支持；重构了部分代码；
 * 后续未来计划：
 * 取消module，用tag取代他；加入七牛存储支持；升级bootstrap版本；界面的改写；
 */
public class Config extends JFinalConfig {

    private boolean isLocal = isLocal();

    /**
     * 配置常量
     */
    public void configConstant(Constants me) {
        if (isLocal) {
            loadPropertyFile("config-test.txt");
        } else {
            loadPropertyFile("config.txt");
        }
        me.setDevMode(isLocal);
        me.setError404View("/common/404.html");
        me.setError500View("/common/500.html");
        me.setBaseViewPath("WEB-INF/template");
        me.setFreeMarkerViewExtension("ftl");
        me.setViewType(ViewType.FREE_MARKER);
        // beetl模版配置工厂
        //me.setMainRenderFactory(new BeetlRenderFactory());
        // freemarker模版配置工厂
//        me.setMainRenderFactory(new FreeMarkerRender(""));
    }

    /**
     * 配置路由
     */
    public void configRoute(Routes me) {
        me.add("/", com.xxs.controller.shop.IndexController.class)
	        .add("/oauth", com.xxs.controller.shop.api.OauthController.class)
        	.add("/member", com.xxs.controller.shop.member.MemberController.class)
        	.add("/seller", com.xxs.controller.shop.seller.SellerController.class)
        	.add("/admin/seller", com.xxs.controller.admin.SellerController.class)
        	.add("/admin/resource", com.xxs.controller.admin.ResourceController.class)
        	.add("/admin/member", com.xxs.controller.admin.MemberController.class)
        	.add("/admin/admin", com.xxs.controller.admin.AdminController.class)
        	.add("/admin/dict", com.xxs.controller.admin.DictController.class)
        	.add("/admin/goods", com.xxs.controller.admin.GoodsController.class)
        	.add("/admin/order", com.xxs.controller.admin.OrderController.class)
        	.add("/admin/common", com.xxs.controller.admin.CommonController.class);
    }

    /**
     * 配置插件
     */
    public void configPlugin(Plugins me) {
        String jdbcUrl  = getProperty("db.jdbcUrl");
        String user     = getProperty("db.user");
        String password = getProperty("db.password");

        // 配置Druid数据库连接池插件
        DruidPlugin dp = new DruidPlugin(jdbcUrl, user, password);
        dp.addFilter(new StatFilter()).addFilter(new Slf4jLogFilter());
        WallFilter wall = new WallFilter();
        wall.setDbType("mysql");
        dp.addFilter(wall);
        me.add(dp);

        ActiveRecordPlugin arp = new ActiveRecordPlugin(dp).setShowSql(isLocal);
        me.add(arp);
        me.add(new EhCachePlugin());
        // 所有配置在 MappingKit 中搞定
     	_MappingKit.mapping(arp);
    }

    /**
     * 配置全局拦截器
     */
    public void configInterceptor(Interceptors me) {
        me.add(new GlobalInterceptor());
    }

    /**
     * 配置处理器
     */
    public void configHandler(Handlers me) {
//        me.add(new ViewTestHandler());
    }

    /**
     * 初始化常量
     */
    public void afterJFinalStart() {
    	try {
        	Configuration cf = FreeMarkerRender.getConfiguration();
        	Map<String, Object> map = new HashMap<String, Object>();
        	map.put("base", JFinal.me().getContextPath());
			map.put("locale", getProperty("locale"));
			map.put("resource_list", new ResourceListDirective());
			map.put("pagination", new PaginationDirective());
//			map.put("setting", SettingUtils.get());
//        	map.put("systemName", getProperty("system.name"));
//        	map.put("systemVersion", getProperty("system.version"));
//        	map.put("systemDescription", getProperty("system.description"));
//        	map.put("systemShowPowered", getProperty("system.show_powered"));
//        	map.put("message", new MessageMethod());
//        	map.put("abbreviate", new AbbreviateMethod());
//        	map.put("currency", new CurrencyMethod());
//        	map.put("flash_message", new FlashMessageDirective());
//        	map.put("current_member", new CurrentMemberDirective());
//        	map.put("pagination", new PaginationDirective());
//        	map.put("seo", new SeoDirective());
//        	map.put("ad_position", new AdPositionDirective());
//        	map.put("member_attribute_list", new MemberAttributeListDirective());
//        	map.put("navigation_list", new NavigationListDirective());
//        	map.put("tag_list", new TagListDirective());
//        	map.put("friend_link_list", new FriendLinkListDirective());
//        	map.put("brand_list", new BrandListDirective());
//        	map.put("article_list", new ArticleListDirective());
//        	map.put("article_category_root_list", new ArticleCategoryRootListDirective());
//        	map.put("article_category_parent_list", new ArticleCategoryParentListDirective());
//        	map.put("article_category_children_list", new ArticleCategoryChildrenListDirective());
//        	map.put("product_list", new ProductListDirective());
//        	map.put("product_category_root_list", new ProductCategoryRootListDirective());
//        	map.put("product_category_parent_list", new ProductCategoryParentListDirective());
//        	map.put("product_category_children_list", new ProductCategoryChildrenListDirective());
//        	map.put("review_list", new ReviewListDirective());
//        	map.put("consultation_list", new ConsultationListDirective());
//        	map.put("promotion_list", new PromotionListDirective());
        	map.put("compress", StandardCompress.INSTANCE);
        	cf.setSharedVaribles(map);
        	
        	cf.setDefaultEncoding(getProperty("template.encoding"));
        	cf.setURLEscapingCharset(getProperty("url_escaping_charset"));
        	cf.setTagSyntax(Configuration.SQUARE_BRACKET_TAG_SYNTAX);
        	cf.setWhitespaceStripping(true);
        	cf.setClassicCompatible(true);
        	cf.setNumberFormat(getProperty("template.number_format"));
        	cf.setBooleanFormat(getProperty("template.boolean_format"));
        	cf.setDateTimeFormat(getProperty("template.datetime_format"));
        	cf.setDateFormat(getProperty("template.date_format"));
        	cf.setTimeFormat(getProperty("template.time_format"));
        	
//        	cf.setSharedVariable("shiro", new ShiroTags());
        	cf.setServletContextForTemplateLoading(JFinal.me().getServletContext(), getProperty("template.loader_path"));
        } catch (TemplateModelException e) {
            e.printStackTrace();
        }
        super.afterJFinalStart();
    }

    // 判断是否本地，目前为判断的机器的类型
    private boolean isLocal(){
        return true;
    }

    public static void main(String[] args) {
        JFinal.start("src/main/webapp", 80, "/", 5);
    }

}